package com.vpen.iot.manager;

import cn.hutool.json.JSONUtil;
import com.vpen.iot.model.dto.TestAppDto;
import com.vpen.iot.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Vpen
 * @date 2024/1/11 17:16
 */
@Slf4j
public class ExportThreadPool extends ThreadPoolExecutor {

    private volatile static ExportThreadPool instance;
    private static final AtomicBoolean isRunning = new AtomicBoolean(false);

    public static ExportThreadPool getInstance() {
        if (instance == null) {
            synchronized (ExportThreadPool.class) {
                if (instance == null) {
                    instance = new ExportThreadPool(1,1,30,TimeUnit.MINUTES);
                }
            }
        }
        return instance;
    }

    public ExportThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, new ArrayBlockingQueue<>(1),new ExportRejectedExecutionHandler());
    }


    @Override
    public Future<?> submit(Runnable task) {
        log.trace("提交任务");
        if (isRunning.get()){
            isRunning.set(true);
            log.trace("当前有任务执行了");
            respose();
            return null;
        }
        isRunning.set(true);
        return super.submit(task);
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        log.debug("前置执行任务");
        super.beforeExecute(t, r);
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        log.debug("后置执行任务");
        // 执行完任务的操作
        isRunning.set(false);
        super.afterExecute(r, t);
    }

    public static class ExportRejectedExecutionHandler implements RejectedExecutionHandler{
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            respose();
        }
    }

    private static void respose(){
        HttpServletResponse response = CommonUtil.getResponse();
        response.setContentType("application/json");
        PrintWriter writer;
        try {
            writer = response.getWriter();
            writer.write(JSONUtil.toJsonStr(new TestAppDto()));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
